package com.quick.util;

import com.quick.domain.ValidationResult;
import org.apache.commons.collections.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.groups.Default;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 功能描述 TODO
 *
 * @Created Time 2017/9/11
 * @Edited Time 2017/9/11
 * @Created by wangxin43
 */
public class ValidateUtils {
    /**
     * 参照JSR 303规范
     * @param obj
     * @return
     * @throws Exception
     */
    public static final Object validateData(Object obj) throws Exception{
        try {
            ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
            Validator validator = validatorFactory.getValidator();
            Set<ConstraintViolation<Object>> set = validator.validate(obj);
            if(!CollectionUtils.isEmpty(set)){
                return obj;
            }
        }catch (Exception e){
            throw e;
        }
        return null;
    }

    /**
     * 参照JSR 303规范
     * 校验并返回错误结果
     * @param obj
     * @param <T>
     * @return
     */
    public static <T> ValidationResult validateEntity(T obj){
        Validator validator =  Validation.buildDefaultValidatorFactory().getValidator();
        ValidationResult result = new ValidationResult();
        Set<ConstraintViolation<T>> set = validator.validate(obj,Default.class);
        boolean flag = false;
        if( CollectionUtils.isNotEmpty(set) ){
            flag = true;
            Map<String,String> errorMsg = new HashMap<String,String>();
            for(ConstraintViolation<T> cv : set){
                errorMsg.put(cv.getPropertyPath().toString(), cv.getMessage());
            }
            result.setErrorMsg(errorMsg);
            result.setObject(obj);
        }
        result.setHasErrors(flag);
        return result;
    }
}
